//
//  BMWShareViewModel.swift
//  BMWShareSDK
//
//  Created by Li Shengbing, (Shengbing.Li@partner.bmw.com) on 2019/6/26.
//  Copyright © 2019年 Li Shengbing, (Shengbing.Li@partner.bmw.com). All rights reserved.
/*
// 1: 增加一个分享平台步骤？
 2-1: 在info.plist中增加
 2-2: 在BMWPlatform中增加title、urlScheme对应
 2-3: 翻译增加:Localizable.strings
 */

import UIKit


protocol BMWShareViewModelProtocol {
    static var rows: Int {get set}
    func dataSourceWithFilterAfter(bmwSharePlatforms: [BMWPlatform], isHiddenIfNotInstallPlatform: Bool) -> [BMWShareModel]
    static func getImageResourceFromSDKBundle(fullImageName: String) -> UIImage
}

class BMWShareViewModel: BMWShareViewModelProtocol {
    
    static let share: BMWShareViewModel = BMWShareViewModel()
    static var rows: Int = 1
    
    func dataSourceWithFilterAfter(bmwSharePlatforms: [BMWPlatform], isHiddenIfNotInstallPlatform: Bool) -> [BMWShareModel] {
        let filterAfterDataSource = self.handleDataSource(bmwSharePlatforms: bmwSharePlatforms, isHiddenIfNotInstallPlatform: isHiddenIfNotInstallPlatform)
        return filterAfterDataSource
    }
    
    /// get image from sdk's bundle imageName
    ///
    /// - Parameter fullImageName: imageName
    /// - Returns: UIImage
    static func getImageResourceFromSDKBundle(fullImageName: String) -> UIImage {
        let identifiers = ["@2x.png", "@3x.png", ".png", ".jpeg", ".jpg"]
        var i = 0
        identifiers.forEach {
            if (fullImageName as NSString).range(of: $0).length > 0 {
                i = i + 1
            }
        }
        if i == 0 {
            assert(false, "sdk's bundle need input complete icon name, as follow: \"shareName@2x.png\"")
        }
        
        let currentBundle = Bundle(for: self)
        guard let path = currentBundle.path(forResource: fullImageName, ofType: nil, inDirectory: "BMWShare.bundle") else {
            assert(false, "can't find image path, please check.")
            return UIImage()
        }
        return UIImage(contentsOfFile: path) ?? UIImage()
    }
    
    /// Handle data source
    ///
    /// - Parameter bmwSharePlatforms: outside will filter's platform
    /// - Returns: Array<Dictionary>
    fileprivate func handleDataSource(bmwSharePlatforms: [BMWPlatform], isHiddenIfNotInstallPlatform: Bool) -> [BMWShareModel] {
        
        /// Get handled's Datas
        var dataSource = self.getPlatformPlist()
        
        /// 微信
        if (!UIApplication.shared.canOpenURL(URL(string: BMWPlatform.weixin.urlScheme)!) && isHiddenIfNotInstallPlatform) || !bmwSharePlatforms.contains(BMWPlatform.weixin) {
            dataSource = dataSource.filter({ $0.title != BMWPlatform.weixin.localizedStringTitle })
        }
        /// 朋友圈
        if (!UIApplication.shared.canOpenURL(URL(string: BMWPlatform.weixin.urlScheme)!) && isHiddenIfNotInstallPlatform) || !bmwSharePlatforms.contains(BMWPlatform.pengyouquan) {
            dataSource = dataSource.filter({ $0.title != BMWPlatform.pengyouquan.localizedStringTitle })
        }
        /// QQ
        if (!UIApplication.shared.canOpenURL(URL(string: BMWPlatform.qq.urlScheme)!) && isHiddenIfNotInstallPlatform) || !bmwSharePlatforms.contains(BMWPlatform.qq) {
            dataSource = dataSource.filter({ $0.title != BMWPlatform.qq.localizedStringTitle })
        }
        /// 微博
        if (!UIApplication.shared.canOpenURL(URL(string: BMWPlatform.weibo.urlScheme)!) && isHiddenIfNotInstallPlatform) || !bmwSharePlatforms.contains(BMWPlatform.weibo) {
            dataSource = dataSource.filter({ $0.title != BMWPlatform.weibo.localizedStringTitle })
        }
        /// 短信
        if (!UIApplication.shared.canOpenURL(URL(string: BMWPlatform.sms.urlScheme)!) && isHiddenIfNotInstallPlatform) || !bmwSharePlatforms.contains(BMWPlatform.sms) {
            dataSource = dataSource.filter({ $0.title != BMWPlatform.sms.localizedStringTitle })
        }
        /// 粘贴板
        if !bmwSharePlatforms.contains(BMWPlatform.copy) {
            dataSource = dataSource.filter({ $0.title != BMWPlatform.copy.localizedStringTitle })
        }
        return dataSource
    }

    /// "/var/containers/Bundle/Application/D7A39CEF-01D9-46AF-9B0B-D23A8738BDF1/BMWShareDemo.app/Frameworks/BMWShareSDK.framework/Platform.plist"
    fileprivate func getPlatformPlist() -> [BMWShareModel] {
        let currentBundle = Bundle(for: BMWShareViewModel.self)
        guard let path = currentBundle.path(forResource: "SharePlatform.plist", ofType: nil) else { return [] }
        guard let dataArray = NSArray(contentsOfFile: path) else { return [] }
        var list = [BMWShareModel]()
        dataArray.forEach {
            guard let dict = $0 as? [String: String] else { return }
            let model = BMWShareModel(dict: dict)
            switch model.title {
            case BMWPlatform.weixin.originTitle:
                model.title = BMWNSLocalizedString.localizedString("BMWSHAREUI_WX_FRIENDS_TITLE", comment: "Wechat Friends")
            case BMWPlatform.pengyouquan.originTitle:
                model.title = BMWNSLocalizedString.localizedString("BMWSHAREUI_WX_CIRCLE_TITLE", comment: "Wechat Circle")
            case BMWPlatform.weibo.originTitle:
                model.title = BMWNSLocalizedString.localizedString("BMWSHAREUI_WB_TITLE", comment: "Weibo")
            case BMWPlatform.sms.originTitle:
                model.title = BMWNSLocalizedString.localizedString("BMWSHAREUI_MESSAGE_TITLE", comment: "Message")
            case BMWPlatform.copy.originTitle:
                model.title = BMWNSLocalizedString.localizedString("BMWSHAREUI_COPY_TITLE", comment: "Copy")
            default:
                break
            }
            list.append(model)
        }
        /// print("getPlatformPlist-list=\(list)")
        return list
    }
}

public enum BMWPlatform {
    case weixin
    case pengyouquan
    case qq
    case weibo
    case sms
    case copy
    
    var originTitle: String {
        switch self {
        case .weixin:
            return "微信好友"
        case .pengyouquan:
            return "微信朋友圈"
        case .qq:
            return "QQ"
        case .weibo:
            return "微博"
        case .sms:
            return "短信"
        case .copy:
            return "拷贝"
        }
    }
    
    var localizedStringTitle: String {
        switch self {
            case .weixin:
                return BMWNSLocalizedString.localizedString("BMWSHAREUI_WX_FRIENDS_TITLE", comment: "Wechat Friends")
            case .pengyouquan:
                return BMWNSLocalizedString.localizedString("BMWSHAREUI_WX_CIRCLE_TITLE", comment: "Wechat Circle")
            case .qq:
                return "QQ"
            case .weibo:
                return BMWNSLocalizedString.localizedString("BMWSHAREUI_WB_TITLE", comment: "Weibo")
            case .sms:
                return BMWNSLocalizedString.localizedString("BMWSHAREUI_MESSAGE_TITLE", comment: "Message")
            case .copy:
                return BMWNSLocalizedString.localizedString("BMWSHAREUI_COPY_TITLE", comment: "Copy")
        }
    }
    
    var urlScheme: String {
        switch self {
            case .weixin:
                return "weixin://"
            case .pengyouquan:
                return "weixin://"
            case .qq:
                return "mqq://"
            case .weibo:
                return "sinaweibo://"
            case .sms:
                return "sms://"
            default:
                return ""
        }
    }
}
